<!-- eslint-disable vue/no-v-model-argument -->
<template>
  <div class="dialogWrap">
    <el-form
      :inline="true"
      label-width="80px"
      class="demo-form-inline"
      :model="curRow"
      :rules="rules"
      ref="userRuleFormRef"
      status-icon
    >
      <el-form-item label="账号" prop="loginName">
        <el-input
          v-model="curRow.loginName"
          placeholder="请输入账号"
          :disabled="!props.isCreateMode"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="curRow.realName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="curRow.tel" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="部门" prop="departmentId">
        <el-input
          v-model="curRow.departmentId"
          style="width: 1px; height: 1px; overflow: hidden"
        />
        <el-cascader
          placeholder="请选择部门"
          v-model="dlgDepartmentVal"
          :options="options"
          :props="props1"
          clearable
          @change="dlgDepartmentValChange"
        />
      </el-form-item>
      <el-form-item label="职务" prop="post">
        <el-input v-model="curRow.post" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="curRow.userType" placeholder="请选择用户类型">
          <el-option
            v-for="item in useGlobal.userTypeDict"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="密码" prop="passwd">
        <el-input v-model="curRow.passwd" type="password" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input
          v-model="reCheckPw"
          type="password"
          placeholder="请输入"
          @blur="onPwBlur"
        />
      </el-form-item>

      <br />
      <el-form-item label="状态" prop="userState">
        <el-radio-group v-model="curRow.userState">
          <el-radio
            v-for="item in useGlobal.userStateDict"
            :label="item.key"
            :key="item.key"
            >{{ item.value }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>

  <div class="btnBarCenter" style="padding-bottom: 20px">
    <el-button type="primary" @click="submitForm(userRuleFormRef)">确定</el-button>
    <el-button type="primary" @click="cancelFn()">取消</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import useGlobal from '@/utils/globalDict'
import axios from '@/utils/axios'

import deptTree from './deptTree.json'

interface FlashInterface {
  loginName: string
  realName: string
  tel: string
  departmentId: string
  post: string
  passwd: string
  userState: string
  departmentPath?: string
}

export default defineComponent({
  name: 'createUser',
  props: {
    row: {
      type: Object,
      required: true
    },
    isCreateMode: Boolean,
    dialogVisible: Boolean
  },
  setup(props, { emit }) {
    const curRow = ref<FlashInterface>(
      JSON.parse(JSON.stringify(props.row)) || {
        loginName: '',
        realName: '',
        tel: '',
        departmentId: '',
        post: '',
        passwd: '',
        userState: ''
      }
    )

    let dlgDepartmentVal: Array<number> = [] // 部门初始值
    const dlgDepartmentValChange = (idVal) => {
      console.log('idVal', idVal)
      // const idVal = dlgDepartmentVal
      // console.log('dlgDepartmentVal', dlgDepartmentVal)

      // getCheckedNodes

      if (idVal) {
        const val = JSON.parse(JSON.stringify(idVal))
        curRow.value.departmentId = String(val[val.length - 1])
        curRow.value.departmentPath = val.join()
      } else {
        curRow.value.departmentId = ''
        curRow.value.departmentPath = ''
      }
      console.log('curRow.value', curRow.value)
    }
    const dataReactive = reactive({
      options: deptTree.result || [],
      props1: {
        value: 'id',
        label: 'departmentName',
        checkStrictly: true
      },
      reCheckPw: '',
      onPwBlur() {
        if (curRow.value.passwd !== dataReactive.reCheckPw) {
          ElMessage.info('两次输入的密码不一致')
        }
      },
      cancelFn() {
        emit('update:modelValue', false)
      },
      getTree() {
        axios.get('/dept/tree').then((res: any) => {
          if (res.success && res.result) {
            dataReactive.options = res.result
          }
        })
      }
    })
    // dataReactive.getTree()

    if (curRow.value.departmentPath) {
      const path = curRow.value.departmentPath.split(',')
      dlgDepartmentVal = path.map((val: string) => {
        return Number(val)
      })
    }
    dataReactive.reCheckPw = curRow.value.passwd || ''

    // 添加表单校验 ⬇⬇⬇
    const userRuleFormRef = ref<FormInstance>()
    const rules = reactive<FormRules>({
      loginName: [
        { required: true, message: '请输入账号', trigger: 'change' },
        {
          pattern: /^[A-Za-z0-9]{1,30}$/,
          message: '请使用字母或数字组合！',
          trigger: 'blur'
        }
      ],
      realName: [
        {
          required: true,
          message: '请输入姓名',
          trigger: 'change'
        },
        {
          pattern: /^[\u4e00-\u9fa5]{0,}$/,
          message: '请输入中文！',
          trigger: 'change'
        }
      ],
      tel: [
        { required: true, message: '请输入手机号', trigger: 'change' },
        {
          pattern: /^(1[2-9][0-9])\d{8}$/,
          message: '手机号码格式不正确！',
          trigger: 'blur'
        }
      ],
      departmentId: [{ required: true, message: '请输入部门', trigger: 'change' }],
      post: [{ required: true, message: '请输入职务', trigger: 'change' }],
      userType: [{ required: true, message: '请输入用户类型', trigger: 'change' }],
      passwd: [{ required: true, message: '请输入密码', trigger: 'change' }],
      userState: [{ required: true, message: '请输入状态', trigger: 'change' }]
    })

    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      // eslint-disable-next-line consistent-return
      await formEl.validate((valid, fields) => {
        if (valid) {
          if (curRow.value.passwd !== dataReactive.reCheckPw) {
            ElMessage.info('两次输入的密码不一致')
            return false
          }
          const params = JSON.parse(JSON.stringify(curRow.value))
          // const idVal = dlgDepartmentVal
          //
          // console.log('idVal', idVal)
          // console.log('params~~~~', params)
          //
          // if (idVal) {
          //   params.departmentId = idVal[idVal.length - 1]
          //   params.departmentPath = dlgDepartmentVal.join()
          // } else {
          //   params.departmentId = ''
          //   params.departmentPath = ''
          // }

          axios.post('/user/save', params).then((res: any) => {
            if (res.success && res.result) {
              ElMessage.success(res.resultDes)

              emit('onFinish')
            } else {
              ElMessage.error(res.resultDes)
            }
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    return {
      ...toRefs(dataReactive),
      dlgDepartmentVal,
      dlgDepartmentValChange,
      curRow,
      props,

      useGlobal,
      rules,
      userRuleFormRef,
      submitForm
    }
  }
})
</script>

<style lang="stylus" scoped>
.el-form-item{
  width:300px
}
</style>
